package com.product_customer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class C {

    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        },"C").start();
    }
}

//如何轮询？
class Data3{

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number =1; //1A 2B 3C

    public void printA(){
        lock.lock();
        try {
            while (number!=1){
                condition1.await();//等待
            }
            System.out.println(Thread.currentThread().getName()+"=>AAAA");
            number=2;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //唤醒指定的人
            condition2.signal();
            lock.unlock();
        }
    }
    public void printB(){
        lock.lock();
        try {
            while (number!=2){
                condition2.await();//等待
            }
            System.out.println(Thread.currentThread().getName()+"=>BBBB");
            number=3;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //唤醒指定的人
            condition3.signal();
            lock.unlock();
        }
    }
    public void printC(){
        lock.lock();
        try {
            while (number!=3){
                condition3.await();//等待
            }
            System.out.println(Thread.currentThread().getName()+"=>CCCC");
            number=1;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //唤醒指定的人
            condition1.signal();
            lock.unlock();
        }
    }

    //生产线： 下单-》支付-》交易-》物流   用这种逻辑顺序执行，if会存在虚假唤醒问题。用while
}
